import { getCategory1ListApi, getCategory2ListApi, getCategory3ListApi } from '@/api/product/category'

export default {
  namespaced: true,
  state: {
    category1Id: '',
    category2Id: '',
    category3Id: '',
    category1List: [],
    category2List: [],
    category3List: []
  },
  mutations: {
    UPDATE_CATEGORY1LIST(state, category1List) {
      state.category1List = category1List
    },
    UPDATE_CATEGORY2LIST(state, category2List) {
      state.category2List = category2List
    },
    UPDATE_CATEGORY3LIST(state, category3List) {
      state.category3List = category3List
    },
    UPDATE_CATEGORY1ID(state, category1Id) {
      state.category1Id = category1Id
    },
    UPDATE_CATEGORY2ID(state, category2Id) {
      state.category2Id = category2Id
    },
    UPDATE_CATEGORY3ID(state, category3Id) {
      state.category3Id = category3Id
    }
  },
  actions: {
    async getCategory1List({ commit }) {
      // console.log(111)
      const res = await getCategory1ListApi()
      res.data = res.data.map(item => {
        return {
          ...item,
          hasChildren: true,
          level: 1
        }
      })
      if (res.code === 200) {
        commit('UPDATE_CATEGORY1LIST', res.data)
      }
    },
    async getCategory2List({ commit }, category1Id) {
      commit('UPDATE_CATEGORY2ID', '')
      commit('UPDATE_CATEGORY3ID', '')
      const res = await getCategory2ListApi(category1Id)
      res.data = res.data.map(item => {
        return {
          ...item,
          level: 2,
          hasChildren: true
        }
      })
      if (res.code === 200) {
        commit('UPDATE_CATEGORY2LIST', res.data)
        commit('UPDATE_CATEGORY1ID', category1Id)
        commit('UPDATE_CATEGORY3LIST', [])
      }
    },
    async getCategory3List({ commit }, category2Id) {
      commit('UPDATE_CATEGORY3ID', '')
      const res = await getCategory3ListApi(category2Id)
      res.data = res.data.map(item => {
        return {
          ...item,
          level: 3,
          hasChildren: false
        }
      })
      if (res.code === 200) {
        commit('UPDATE_CATEGORY3LIST', res.data)
        commit('UPDATE_CATEGORY2ID', category2Id)
      }
    }
  },
  getters: {
    category1Id(state) {
      return state.category1Id
    },
    category2Id(state) {
      return state.category2Id
    },
    category3Id(state) {
      return state.category3Id
    }
  }
}
